import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:safetymonitor/app/components/common/no_permissions_widget.dart';
import 'package:safetymonitor/app/components/custom_app_bar.dart';
import 'package:safetymonitor/app/components/custom_modele/custom_multiple_bottom_sheet.dart';
import 'package:safetymonitor/app/components/custom_modele/custom_title_chart_page.dart';
import 'package:safetymonitor/app/core/core.dart';
import 'package:safetymonitor/app/core/ext/widget_extension.dart';
import 'package:safetymonitor/app/core/http/http.dart';
import 'package:safetymonitor/app/core/utils/interface.dart';
import 'package:safetymonitor/app/core/utils/user_manager.dart';
import 'package:safetymonitor/app/data/entities/application/corporation_name_entity.dart';
import 'package:safetymonitor/app/data/entities/application/device_type_tree_new_entity.dart';
import 'package:safetymonitor/app/data/entities/application/get_device_info_entity.dart';
import 'package:safetymonitor/generated/assets.dart';
import 'package:safetymonitor/router/app_pages.dart';

/// 设备管理
class DeviceManger extends StatefulWidget {
  const DeviceManger({super.key});

  @override
  State<DeviceManger> createState() => _DeviceMangerState();
}

class _DeviceMangerState extends State<DeviceManger> {
  ///主公司 写死（默认）
  String currentMainCompany = '金钼集团';

  ///获取账号的当前公司名字
  String? userCompanyName;

  // 公司列表
  List<CorporationNameEntity> _nameList = [];

  // 选中的公司
  CorporationNameEntity? _selectId;

  // 设备列表
  List<DeviceTypeTreeNewTreeSelects> _deviceList = [];

  // 选中的设备
  DeviceTypeTreeNewTreeSelects? _selectDevice;

  // 获取信息列表
  List<GetDeviceInfoEntity> _infoList = [];

  @override
  void initState() {
    super.initState();
    //获得部门信息 根据登录的部门id查询当前的公司信息（有主公司和分公司）
    userCompanyName = UserManager.getUserCompanyName() ?? '';
    // deptGet();
    _getDepartmentList();
  }

  // void deptGet() async {
  //   final res = await HttpUtil().generateGetRequest<DeptGetEntityEntity>(
  //     Interface.deptGet,
  //     queryParameters: {
  //       'id': UserManager.getUser()?.dept.id,
  //     },
  //   ).execute();
  //   res.onSuccess((result) {
  //     if (result.data != null) {
  //       final DeptGetEntityEntity? deptGetEntityEntity = result.data;
  //       //获取当前公司名字
  //       userCompanyName = deptGetEntityEntity?.name;
  //       setState(() {
  //
  //       });
  //     }
  //   });
  // }

  @override
  Widget build(BuildContext context) {
    if (!isNotPermissions) {
      return const NoPermissionsWidget();
    }

    return Scaffold(
      backgroundColor: AppColors.bg_page_color,
      appBar: CustomAppBar(
        titleText: '监测设备',
      ),
      body: Padding(
        padding: const EdgeInsets.only(
          top: 12,
          left: 16,
          right: 16,
        ),
        child: Column(
          children: [
            _getSearchEnterWidget(),
            AppGaps.vGap8,
            // AppGaps.vGap8,
            //数据库都是直接写进去的数据 都没走接口的
            // SizedBox(
            //   // height: _deviceList.isNotEmpty ? AppDimens.dp30 : AppDimens.dp0,
            //   height: _deviceList.isNotEmpty ? AppDimens.dp0 : AppDimens.dp0,
            //   child: Padding(
            //     padding: EdgeInsets.only(bottom: 10.w),
            //     child: ListView.separated(
            //         scrollDirection: Axis.horizontal,
            //         itemCount: _deviceList.length,
            //         itemBuilder: (context, index) {
            //           return Container(
            //             padding: const EdgeInsets.symmetric(horizontal: 15),
            //             alignment: Alignment.center,
            //             decoration: BoxDecoration(
            //               color: _selectDevice?.id == _deviceList[index].id
            //                   ? Colors.blue
            //                   : Colors.grey[100],
            //               borderRadius: BorderRadius.circular(14),
            //             ),
            //             child: Text(
            //               '${_deviceList[index].label}',
            //               style: TextStyle(
            //                 color: _selectDevice?.id == _deviceList[index].id
            //                     ? Colors.white
            //                     : Colors.black,
            //                 fontSize: 14,
            //               ),
            //             ),
            //           ).click(() {
            //             if (_selectDevice?.id == _deviceList[index].id) {
            //               _selectDevice = null;
            //             } else {
            //               _selectDevice = _deviceList[index];
            //             }
            //             setState(() {});
            //             _getDeviceList();
            //           });
            //         },
            //         separatorBuilder: (context, index) {
            //           return const SizedBox(
            //             width: 8,
            //           );
            //         }),
            //   ),
            // ),
            Expanded(
              child: _buildVideoList(),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildSelect() {
    return Container(
      height: 38.w,
      decoration: BoxDecoration(
        color: Colors.white,
        // border: Border.all(color: const Color(0xffDCE1EA)),
        // borderRadius: BorderRadius.circular(6),
      ),
      child: Row(
        children: [
          const SizedBox(
            width: 12,
          ),
          Text(
            _getString(),
            style: TextStyles.grey_14,
            maxLines: 1,
          ),
          Visibility(
            visible: currentMainCompany == userCompanyName,
            child: const Icon(
              Icons.keyboard_arrow_down,
              color: AppColors.font_color_gray,
            ),
          ),
        ],
      ),
    ).clickOnce(_selectCompany);
  }

  // 构建空数据提示
  Widget _buildEmptyWidget() {
    return CustomScrollView(
      slivers: [
        SliverFillViewport(
          delegate: SliverChildBuilderDelegate(
            (context, index) {
              return Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  SvgPicture.asset(Assets.svgIconNone, height: 300.w),
                  Text(
                    '-- 暂无数据 --',
                    style: TextStyle(
                        fontSize: 14.w,
                        height: 1.2,
                        color: const Color(0xff4D5956),
                        fontWeight: FontWeight.w400),
                  )
                ],
              );
            },
            childCount: 1,
          ),
        )
      ],
    );
  }

  Widget _buildVideoList() {
    return EasyRefresh(
      onRefresh: () async {
        _getDeviceList();
      },
      child: _infoList.isNotEmpty
          ? ListView.separated(
              itemCount: _infoList.length,
              separatorBuilder: (context, index) {
                return AppGaps.vGap16;
              },
              itemBuilder: (context, index) {
                return CustomTitleChartPage(
                  titleRightWidget: Container(
                    padding: EdgeInsets.only(left: 5.w,top: 5.w,bottom: 5.w),
                    child: Text(
                      '维护日志',
                      style: TextStyle(
                        color: Colors.blue,
                        fontWeight: FontWeight.w500,
                        fontSize: 14.sp,
                      ),
                    ),
                  ).clickOnce((){
                    //维护日志界面
                    Get.toNamed(Routes.maintainLogs,arguments: _infoList[index].id);
                  }),
                  contentPadding: EdgeInsets.only(left: 16.w, top: 16.w),
                  title:
                      '${_infoList[index].deviceName} / 设备编码:${_infoList[index].deviceCode}',
                  child: Stack(
                    children: [
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            children: [
                              Expanded(
                                  child: _getTextView(
                                      title: '设备类型:',
                                      value:
                                          '${_infoList[index].deviceTypeName}')),
                              Expanded(
                                  child: _getTextView(
                                      title: '设备等级:',
                                      value:
                                          '${_infoList[index].deviceLevelName}')),
                            ],
                          ),
                          _getTextView(
                              title: '所属机构:',
                              value: '${_infoList[index].companyName?.trim()}'),
                          _getTextView(
                              title: '是否投用:',
                              value: _infoList[index].isUse == 1 ? '是' : '否'),
                          AppGaps.vGap6,
                        ],
                      ),
                      Positioned(
                        right: 0,
                        bottom: 0,
                        child: SizedBox(
                          width: 56.w,
                          height: 36.w,
                          child: Stack(
                            alignment: Alignment.center,
                            children: [
                              SvgPicture.asset(
                                Assets.svgIconEnter,
                                fit: BoxFit.cover,
                              ),
                              Icon(
                                Icons.arrow_forward,
                                size: 20.w,
                                color: Colors.white,
                              ).marginOnly(left: 7.w, top: 6.w)
                            ],
                          ),
                        ),
                      )
                    ],
                  ).clickOnce(() {
                    _toDetails(index);
                  }),
                );
              })
          : _buildEmptyWidget(),
    );
  }

  /// 获取字段显示
  Widget _getTextView({required String title, required String value}) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              title,
              style: TextStyle(
                fontSize: 14.sp,
                height: 1.2,
                fontWeight: FontWeight.w400,
                color: const Color(0xffC7CEE5),
              ),
            ),
            AppGaps.hGap6,
            Expanded(
                child: Text(
              value,
              style: TextStyle(
                fontSize: 14.sp,
                height: 1.2,
                fontWeight: FontWeight.w400,
                color: const Color(0xff1D3452),
              ),
            ))
          ],
        ),
        AppGaps.vGap10,
      ],
    );
  }

  // 跳转详情
  void _toDetails(int index) {
    Get.toNamed(Routes.deviceManagementDetail, arguments: _infoList[index]);
  }

  String _getString() {
    if (_selectId != null) {
      return _selectId!.name!.trim();
    }
    return '公司名';
  }

  // 获取部门列表
  void _getDepartmentList() async {
    final res = await HttpUtil()
        .generateGetRequest<List<CorporationNameEntity>>(Interface.deptList,
            queryParameters: {
          'flag': 2,
        }).execute();
    res.onSuccess((result) {
      if (result.data != null) {
        // _selectId = result.data!.first;
        _nameList = result.data!;
        _getDeviceType(_selectId?.id);
      }
    });
  }

  // 选取公司
  void _selectCompany() {
    CustomEquipmentBottomSheet<CorporationNameEntity>(
      dataList: _nameList,
      checkedList: _selectId != null ? [_selectId!] : [],
      onConfirm: (value) {
        if (value.isNotEmpty) {
          _selectId = value[0];
          setState(() {});
          _getDeviceType(_selectId?.id);
        }
      },
      title: '选择公司',
      isMultiple: false,
    ).showBottomSheetDialog();
  }

  // 获取设备类型
  void _getDeviceType(int? id) async {
    // final res = await HttpUtil()
    //     .generateGetRequest<List<DeviceTypeTreeNewEntity>>(
    //         Interface.getDeviceType,
    //         queryParameters: {'companyId': id}).execute();
    // res.onSuccess((result) {
    //   if (result.data != null) {
    //     if (result.data!.isNotEmpty) {
    //       final List<DeviceTypeTreeNewEntity> list = result.data!;
    //       _deviceList = list[0].treeSelects;
    //       print('list[0].treeSelects${list[0].treeSelects}');
    //     }
    //   }
    //   setState(() {});
      _getDeviceList();
    // });
    // final res = await HttpUtil().generateGetRequest<List<DeviceTreeEntity>>(Interface.getDeviceType, queryParameters: {'companyId': id}).execute();
    // res.onSuccess((result) {
    //   if (result.data != null) {
    //     _deviceList.clear();
    //     if (result.data!.isNotEmpty) {
    //       final list = result.data!;
    //       for (var i in list) {
    //         if (i.children != null && i.children!.isNotEmpty) {
    //           for (var j in i.children!) {
    //             _deviceList.add(j);
    //           }
    //         } else {
    //           _deviceList.add(DeviceTreeChildren(
    //             id: i.id,
    //             label: i.label,
    //             code: i.code,
    //             sort: i.sort,
    //             parentId: i.parentId,
    //           ));
    //         }
    //       }
    //     }
    //   }
    //   setState(() {});
    //   _getDeviceList();
    // });
  }
  bool isNotPermissions=true;
  //获取设备列表
  void _getDeviceList() async {
    _infoList.clear();
    final res = await HttpUtil().generateGetRequest<List<GetDeviceInfoEntity>>(
        Interface.getDeviceList,
        queryParameters: {
          'companyId': _selectId?.id,
          'deviceTypeId': _selectDevice?.id,
          'pageNo': 1,
          'pageSize': 100,
          'deviceName': searchX,
        }).execute();
    res.onSuccess((result) {
      if (result.data != null) {
        _infoList = result.data!;
      }
      isNotPermissions=true;
      setState(() {
        // 恢复光标位置
        _controller.selection =
            selection ?? const TextSelection(baseOffset: 0, extentOffset: 0);
      });
    });
    res.onError((result) {
      if(result.code==403&&result.message=='没有该操作权限'){
        isNotPermissions=false;
        setState(() {});
      }
    });
  }

  final TextEditingController _controller = TextEditingController();

  String searchX = '';
  TextSelection? selection;

  ///搜索框
  Widget _getSearchEnterWidget() {
    return Container(
        height: 38.w,
        padding: EdgeInsets.only(left: 12.w),
        alignment: Alignment.center,
        decoration: BoxDecoration(
            color: Colors.white,
            border: Border.all(color: const Color(0xffF0F0F0), width: 1.w),
            borderRadius: BorderRadius.all(Radius.circular(8.w))),
        child: Row(
          children: [
            SvgPicture.asset(
              'assets/svg/icon_search.svg',
              width: 16.w,
            ),
            Expanded(
                child: TextField(
                    keyboardType: TextInputType.text,
                    textInputAction: TextInputAction.done,
                    controller: _controller,
                    onChanged: (value) {
                      // 当文本改变时，保存光标位置
                      selection = _controller.selection;
                      // 执行任何你需要的操作，比如删除字符
                      searchX = value;
                      // 恢复光标位置
                      _getDeviceList();
                    },
                    style: TextStyle(
                        color: const Color(0xff222222),
                        fontWeight: FontWeight.w400,
                        fontSize: 14.sp),
                    decoration: InputDecoration(
                      counterText: '',
                      //防止适配不居中
                      isCollapsed: true,
                      border:
                          const OutlineInputBorder(borderSide: BorderSide.none),
                      contentPadding: EdgeInsets.only(left: 8.w),
                      hintText: '请输入设备名称',
                      hintStyle: TextStyle(
                          fontSize: 14.sp,
                          fontWeight: FontWeight.w400,
                          color: const Color(0xffA0A7B5)),
                    ))),
            //】子公司登入查看设备管理，上面选择公司操作默认公司名称，不让用户操作
            if (currentMainCompany == userCompanyName)_buildSelect(),
          ],
        ));
  }
}
